package at.fhj.swd.pse.helper;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;

import org.jboss.logging.Logger;

import at.fhj.swd.pse.entities.User;

@SessionScoped
public class UserManager implements Serializable {
	private static final long serialVersionUID = 1L;

	@PersistenceContext
	private EntityManager em;

	@Named
	private User activeUser;

	private static final Logger logger = Logger.getLogger(UserManager.class);

	public UserManager() {

	}

	@PostConstruct
	public void init() {
		logger.info("init");
	}

	public User getUserProfileByUserId(final int userId) {
		logger.info("UserManager - getUserProfileByUserId: " + userId);
		User userProfile = this.em.find(User.class, userId);
		if (userProfile == null) {
			throw new EntityNotFoundException("Can't find User Profile for User-ID " + userId);
		}
		return userProfile;
	}

	public User getActiveUser() {
		return this.activeUser;
	}

	public void setActiveUser(final User activeUser) {
		logger.info("UserManager - setActiveUser: " + activeUser.getId());
		this.activeUser = activeUser;
	}

	public void updateUser(User user) {
		logger.info("Update user: " + user.getUsername());
		em.merge(user);
	}
}
